import ProgressHUD
import UIKit

struct ShareModel: Codable {
  let imagePath: String?
  let miniprogramType: Int
  let path: String
  let title: String
  let userName: String?
  let webpageUrl: String
  let withShareTicket: String
}

// MARK: - Models
struct Category: Codable {
  let id: Int
  let name: String?  // ✅ 让 name 变成可选
  var isSelected: Bool = false

  enum CodingKeys: String, CodingKey {
    case id = "categoryId"
    case name = "categoryName"
  }

  init(id: Int, name: String?, isSelected: Bool) {
    self.id = id
    self.name = name
    self.isSelected = isSelected
  }

  init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)
    id = try container.decode(Int.self, forKey: .id)
    name = try container.decodeIfPresent(String.self, forKey: .name)  // ✅ 使用 decodeIfPresent
  }

  func encode(to encoder: Encoder) throws {
    var container = encoder.container(keyedBy: CodingKeys.self)
    try container.encode(id, forKey: .id)
    try container.encodeIfPresent(name, forKey: .name)  // ✅ 避免 nil 导致编码错误
  }
}

enum FollowType {
  case followGoods
  case unfollowGoods

  static let unfollowString = "unfollowGoods"
  static let followString = "followGoods"
}

struct Product: Codable {
  let spuId: Int
  let categoryId: Int
  let categoryName: String?
  let spuName: String
  let mainImage: String
  let saleCount: Int  // 销量
  let gmv: Int
  let promotionPrice: Int  // gmv使用价格
  let publishStatus: Int  // 0 未上架, 1 上架中
  let followStatus: Int  // 0-未关注 1-已关注
  let showStatus: Int  // 0 隐藏品 1正常品
}

struct FilterItem {
  let title: String
  var showArrow: Bool
  var id: Int
  var key: String
}

class ProductListViewController: UIViewController {

  // MARK: - Properties
  private var categories: [Category] = [
    Category(id: -1, name: "全部商品", isSelected: true)
  ]
  private var allProducts: [Product] = []
  private var displayedProducts: [Product] = []
  private var currentCategoryId: Int = -1

  private let taskId: Int

  init(taskId: Int) {
    self.taskId = taskId
    super.init(nibName: nil, bundle: nil)
  }

  required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }

  // MARK: - UI Components
  private lazy var searchContainerView: UIView = {
    let view = UIView()
    view.translatesAutoresizingMaskIntoConstraints = false
    view.backgroundColor = .white
    return view
  }()

  // 搜索的防抖
  private var debounceWorkItem: DispatchWorkItem?

  private lazy var searchBar: UISearchBar = {
    let searchBar = UISearchBar()
    searchBar.translatesAutoresizingMaskIntoConstraints = false
    searchBar.placeholder = "请输入商品名称"
    searchBar.searchBarStyle = .minimal
    searchBar.delegate = self
    if let textField = searchBar.value(forKey: "searchField") as? UITextField {
      textField.returnKeyType = .done
    }
    return searchBar
  }()

  private lazy var batchShareButton: UIButton = {
    let button = UIButton(type: .system)
    button.translatesAutoresizingMaskIntoConstraints = false
    button.setTitle("批量分享", for: .normal)
    button.setTitleColor(.white, for: .normal)
    button.backgroundColor = UIColor(red: 241 / 255, green: 123 / 255, blue: 69 / 255, alpha: 1)
    button.layer.cornerRadius = 4
    button.titleLabel?.font = .systemFont(ofSize: 14)
    return button
  }()

  private lazy var filterScrollView: UIScrollView = {
    let scrollView = UIScrollView()
    scrollView.translatesAutoresizingMaskIntoConstraints = false
    scrollView.showsHorizontalScrollIndicator = false
    scrollView.backgroundColor = .white
    return scrollView
  }()

  private lazy var filterStackView: UIStackView = {
    let stackView = UIStackView()
    stackView.translatesAutoresizingMaskIntoConstraints = false
    stackView.axis = .horizontal
    stackView.spacing = 12
    stackView.distribution = .fillProportionally
    return stackView
  }()

  // 添加左侧分类列表
  private lazy var categoryTableView: UITableView = {
    let table = UITableView()
    table.translatesAutoresizingMaskIntoConstraints = false
    table.register(CategoryCell.self, forCellReuseIdentifier: "CategoryCell")
    table.delegate = self
    table.dataSource = self
    table.separatorStyle = .none
    table.backgroundColor = .systemGray6
    table.keyboardDismissMode = .onDrag
    return table
  }()

  // 重命名原来的tableView为productTableView
  private lazy var productTableView: UITableView = {
    let table = UITableView()
    table.translatesAutoresizingMaskIntoConstraints = false
    table.register(ProductCell.self, forCellReuseIdentifier: "ProductCell")
    table.delegate = self
    table.dataSource = self
    table.separatorStyle = .none
    table.keyboardDismissMode = .onDrag
    //        table.estimatedRowHeight = 200
    //        table.rowHeight = UITableView.automaticDimension
    return table
  }()

  // MARK: - Lifecycle
  override func viewDidLoad() {
    super.viewDidLoad()
    setupUI()
    enableSmartTapToDismissKeyboard()
  }

  let mobPageName = "app-商品"
  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    MobClick.beginLogPageView(mobPageName)
    loadData()
  }

  override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    MobClick.endLogPageView(mobPageName)
  }

  // MARK: - Setup
  private func setupUI() {
    view.backgroundColor = .white
    title = "商品"

    // 添加视图
    view.addSubview(searchContainerView)
    searchContainerView.addSubview(searchBar)
    //        searchContainerView.addSubview(batchShareButton)

    view.addSubview(filterScrollView)
    filterScrollView.addSubview(filterStackView)

    view.addSubview(categoryTableView)
    view.addSubview(productTableView)

    setupConstraints()
    setupFilterButtons()
  }

  private func setupConstraints() {
    NSLayoutConstraint.activate([
      // 搜索容器视图约束
      searchContainerView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
      searchContainerView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
      searchContainerView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
      searchContainerView.heightAnchor.constraint(equalToConstant: 60),

      // 搜索栏约束
      searchBar.leadingAnchor.constraint(equalTo: searchContainerView.leadingAnchor, constant: 8),
      searchBar.centerYAnchor.constraint(equalTo: searchContainerView.centerYAnchor),
      //            searchBar.trailingAnchor.constraint(equalTo: batchShareButton.leadingAnchor),
      searchBar.trailingAnchor.constraint(equalTo: searchContainerView.trailingAnchor),

      // 批量分享按钮约束
      //            batchShareButton.centerYAnchor.constraint(equalTo: searchContainerView.centerYAnchor),
      //            batchShareButton.trailingAnchor.constraint(equalTo: searchContainerView.trailingAnchor, constant: -8),
      //            batchShareButton.widthAnchor.constraint(equalToConstant: 80),
      //            batchShareButton.heightAnchor.constraint(equalToConstant: 32),

      // 分类列表约束
      categoryTableView.topAnchor.constraint(equalTo: searchContainerView.bottomAnchor),
      categoryTableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
      categoryTableView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
      categoryTableView.widthAnchor.constraint(equalToConstant: 90),

      // 筛选滚动视图约束
      filterScrollView.topAnchor.constraint(equalTo: searchContainerView.bottomAnchor),
      filterScrollView.leadingAnchor.constraint(equalTo: categoryTableView.trailingAnchor),
      filterScrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
      filterScrollView.heightAnchor.constraint(equalToConstant: 44),

      // 筛选栈视图约束
      filterStackView.leadingAnchor.constraint(
        equalTo: filterScrollView.leadingAnchor, constant: 15),
      filterStackView.trailingAnchor.constraint(
        equalTo: filterScrollView.trailingAnchor, constant: -15),
      filterStackView.topAnchor.constraint(equalTo: filterScrollView.topAnchor),
      filterStackView.bottomAnchor.constraint(equalTo: filterScrollView.bottomAnchor),
      filterStackView.heightAnchor.constraint(equalTo: filterScrollView.heightAnchor),

      // 商品列表约束
      productTableView.topAnchor.constraint(equalTo: filterScrollView.bottomAnchor),
      productTableView.leadingAnchor.constraint(equalTo: categoryTableView.trailingAnchor),
      productTableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
      productTableView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
    ])

    // 添加分割线
    let separator = UIView()
    separator.translatesAutoresizingMaskIntoConstraints = false
    separator.backgroundColor = .systemGray5
    filterScrollView.addSubview(separator)

    NSLayoutConstraint.activate([
      separator.leadingAnchor.constraint(equalTo: filterScrollView.leadingAnchor),
      separator.trailingAnchor.constraint(equalTo: filterScrollView.trailingAnchor),
      separator.bottomAnchor.constraint(equalTo: filterScrollView.bottomAnchor),
      separator.heightAnchor.constraint(equalToConstant: 0.5),
    ])
  }

  // 筛选按钮管理
  let manager = SortButtonManager()

  private func setupFilterButtons() {
    let filterItems = [
      FilterItem(title: "综合", showArrow: false, id: 1, key: "COMPREHENSIVE"),
      FilterItem(title: "GMV", showArrow: true, id: 2, key: "GMV"),
      FilterItem(title: "销量", showArrow: true, id: 3, key: "SALE_COUNT"),
      FilterItem(title: "价格", showArrow: true, id: 4, key: "SALE_PRICE"),
      //            FilterItem(title: "已上架", showArrow: false, id: 5, key: "isPublish"),
      //            FilterItem(title: "隐藏品", showArrow: false, id: 6, key: "hiddenGood"),
    ]

    for item in filterItems {

      if item.showArrow {
        let button = SortButton(type: .system)
        button.onSortChanged = { [weak self] state in
          guard let self = self else { return }
          let body: [String: Any]
          switch state {
          case .none:
            body = buildSortBody()
          case .ascending:
            body = buildSortBody(orderKey: item.key, asc: true)
          case .descending:
            body = buildSortBody(orderKey: item.key, asc: false)
          }
          MobClick.event("goods_sort", attributes: ["title": item.title, "key": item.key])
          self.loadProducts(body)
        }
        manager.addButton(button)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.setTitle(item.title, for: .normal)
        button.setTitleColor(.black, for: .normal)
        button.titleLabel?.font = .systemFont(ofSize: 13)
        filterStackView.addArrangedSubview(button)
      } else {
        let button = SelectButton(type: .system)
        button.onSelectedChanged = { [weak self] select in
          guard let self = self else { return }
          var body: [String: Any] = buildSortBody()
          if item.key == "isPublish" {
            body = buildSortBody(isPublish: select)
          } else if item.key == "hiddenGood" {
            body = buildSortBody(hiddenGood: select)
          }
          self.loadProducts(body)
        }
        manager.addButton(button)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.setTitle(item.title, for: .normal)
        button.setTitleColor(.black, for: .normal)
        button.titleLabel?.font = .systemFont(ofSize: 13)
        filterStackView.addArrangedSubview(button)
      }

    }
  }

  // MARK: - Data Management
  private func loadData() {
    loadCategorys()
    loadProducts(buildSortBody())
  }

  private func loadCategorys() {
    // 分类
    HttpClient.shared.postWithAutoHUD(endpoint: "/goods/category/list", body: ["taskId": taskId]) {
      [weak self] (categorys: [Category]?) in
      guard let self = self else { return }
      if let categorys = categorys {
        // 根据 currentCategoryId 设置选中状态
        self.categories = categorys.map { category in
          var updatedCategory = category
          updatedCategory.isSelected = (category.id == self.currentCategoryId)
          return updatedCategory
        }
        DispatchQueue.main.async {
          self.categoryTableView.reloadData()
        }
      }
    }
  }

  private func buildSortBody(
    orderKey: String? = "", asc: Bool? = false, isPublish: Bool? = false, hiddenGood: Bool? = false
  ) -> [String: Any] {
    let body =
      [
        "taskId": taskId,
        "searchText": searchBar.text ?? "",
        "categoryId": currentCategoryId,  //  -1表示全部，具体分类填上面接口返回的id
        "isPublish": isPublish!,  // true-上架中  false-全部
        "hiddenGood": hiddenGood!,  // true-隐藏品 false-全部
        "orderRule": [
          "orderByKey": orderKey!,
          "asc": asc!,
        ],
      ] as [String: Any]
    return body
  }

  private func loadProducts(_ body: [String: Any]) {
    // 商品
    HttpClient.shared.postWithAutoHUD(endpoint: "/goods/list", body: body) {
      [weak self] (products: [Product]?) in
      guard let self = self else { return }
      if let products = products {
        self.allProducts = products
        DispatchQueue.main.async {
          self.displayedProducts = self.allProducts
          self.productTableView.reloadData()
        }
      }
    }
  }

  private func followGood(spuId: Int, followType: FollowType) {
    let body = [
      "taskId": taskId,
      "spuId": spuId,
    ]

    let endpoint = followType == .followGoods ? FollowType.followString : FollowType.unfollowString
    HttpClient.shared
      .postWithAutoHUD(endpoint: "/goods/\(endpoint)", body: body) {
        [weak self]
        (
          success: String?
        ) in
        guard let self = self else { return }
        ProgressHUD.succeed(success)
        let body = buildSortBody()
        self.loadProducts(body)
      }
  }
}

// MARK: - UITableViewDelegate & DataSource
extension ProductListViewController: UITableViewDelegate, UITableViewDataSource {
  func numberOfSections(in tableView: UITableView) -> Int {
    return 1
  }

  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if tableView == categoryTableView {
      return categories.count
    } else {
      return displayedProducts.count
    }
  }

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if tableView == categoryTableView {
      let cell =
        tableView.dequeueReusableCell(withIdentifier: "CategoryCell", for: indexPath)
        as! CategoryCell
      let category = categories[indexPath.row]
      cell.configure(with: category)
      return cell
    } else {
      let cell =
        tableView.dequeueReusableCell(withIdentifier: "ProductCell", for: indexPath) as! ProductCell
      let product = displayedProducts[indexPath.row]
      cell.configure(with: product)
      cell.selectionStyle = .none
      cell.onLikeButtonTapped = { [weak self] in
        guard let self = self else { return }
        // 0-未关注 1-已关注
        if product.followStatus == 0 {
          self.followGood(spuId: product.spuId, followType: .followGoods)
        } else {
          self.followGood(spuId: product.spuId, followType: .unfollowGoods)
        }
      }
      cell.onShareButtonTapped = { [weak self] in
        guard let self = self else { return }
        self.shareAction(body: ["taskId": taskId, "spuId": product.spuId])
      }
      return cell
    }
  }

  func shareAction(body: [String: Any]) {
    // 分类
    HttpClient.shared.postWithAutoHUD(endpoint: "/goods/share", body: body) {
      (result: ShareModel?) in
      guard let share = result else {
        print("Failed to get valid image path or URL")
        return
      }
      let shareModel = WXShareModel(
        text: share.title, imagePath: share.imagePath, entranceMiniProgramUsername: share.userName,
        entranceMiniProgramPath: share.path, webpageUrl: share.webpageUrl,
        miniprogramType: share.miniprogramType, withShareTicket: share.withShareTicket)
      WXApi.shareAction(share: shareModel)
    }
  }
  func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if tableView == categoryTableView {
      return 44
    }
    return UITableView.automaticDimension
  }

  func tableView(
    _ tableView: UITableView,
    didSelectRowAt indexPath: IndexPath
  ) {
    if tableView == categoryTableView {
      let selectedCategory = categories[indexPath.row]
      currentCategoryId = selectedCategory.id
      let body = buildSortBody()
      loadProducts(body)

      // 更新分类选中状态
      categories = categories.map { category in
        var updatedCategory = category
        updatedCategory.isSelected = (category.id == selectedCategory.id)
        return updatedCategory
      }
      categoryTableView.reloadData()
    }
  }

}

// MARK: - UISearchBarDelegate
extension ProductListViewController: UISearchBarDelegate {
  func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    // 实现搜索逻辑
    if let textField = searchBar.value(forKey: "searchField") as? UITextField,
      textField.markedTextRange != nil
    {
      return
    }
    debounceWorkItem?.cancel()

    let workItem = DispatchWorkItem { [weak self] in
      guard let self = self else { return }
      let body = buildSortBody()
      loadProducts(body)
    }

    debounceWorkItem = workItem
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.3, execute: workItem)

  }

  func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    searchBar.resignFirstResponder()
  }
}

// MARK: - ProductCell
class ProductCell: UITableViewCell {

  var onLikeButtonTapped: (() -> Void)?
  var onShareButtonTapped: (() -> Void)?

  // MARK: - UI Components
  private let productImageView: UIImageView = {
    let imageView = UIImageView()
    imageView.translatesAutoresizingMaskIntoConstraints = false
    imageView.backgroundColor = UIColor(
      red: 241 / 255, green: 123 / 255, blue: 69 / 255, alpha: 0.1)
    imageView.layer.cornerRadius = 8
    imageView.clipsToBounds = true
    return imageView
  }()

  private let statusLabel: UILabel = {
    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false
    label.backgroundColor = UIColor(red: 82 / 255, green: 196 / 255, blue: 26 / 255, alpha: 1)
    label.textColor = .white
    label.font = .systemFont(ofSize: 10)
    label.textAlignment = .center
    label.layer.cornerRadius = 4
    label.clipsToBounds = true
    return label
  }()

  private let nameLabel: UILabel = {
    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false
    label.font = .systemFont(ofSize: 16, weight: .medium)
    label.numberOfLines = 2
    return label
  }()

  private let priceLabel: UILabel = {
    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false
    label.font = .systemFont(ofSize: 18, weight: .bold)
    label.textColor = UIColor(red: 254 / 255, green: 46 / 255, blue: 46 / 255, alpha: 1)
    return label
  }()

  private let statsLabel: UILabel = {
    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false
    label.font = .systemFont(ofSize: 12)
    label.textColor = .gray
    return label
  }()

  private lazy var likeButton: UIButton = {
    let button = UIButton(type: .system)
    button.translatesAutoresizingMaskIntoConstraints = false
    //        let config = UIImage.SymbolConfiguration(pointSize: 16)
    //        button.setImage(UIImage(systemName: "heart", withConfiguration: config), for: .normal)
    //        button.setImage(UIImage(named: "like_icon_add"), for: .normal)
    //        button.tintColor = .systemPink
    button.layer.cornerRadius = 4.0
    button.layer.masksToBounds = true
    button.addTarget(self, action: #selector(likeAction), for: .touchUpInside)
    return button
  }()

  private lazy var shareButton: UIButton = {
    let button = UIButton(type: .system)
    button.translatesAutoresizingMaskIntoConstraints = false
    button.setTitle("分享", for: .normal)
    button.setTitleColor(.white, for: .normal)
    button.backgroundColor = UIColor(red: 241 / 255, green: 123 / 255, blue: 69 / 255, alpha: 1)
    button.layer.cornerRadius = 4
    button.titleLabel?.font = .systemFont(ofSize: 13)
    button.addTarget(self, action: #selector(shareAction), for: .touchUpInside)
    return button
  }()

  // MARK: - Init
  override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    setupUI()
  }

  required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }

  // MARK: - Setup
  private func setupUI() {
    contentView.addSubview(productImageView)
    productImageView.addSubview(statusLabel)
    contentView.addSubview(nameLabel)
    contentView.addSubview(priceLabel)
    contentView.addSubview(statsLabel)
    contentView.addSubview(likeButton)
    contentView.addSubview(shareButton)

    NSLayoutConstraint.activate([
      productImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 8),
      //            productImageView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor),
      productImageView.widthAnchor.constraint(equalToConstant: 90),
      productImageView.heightAnchor.constraint(equalToConstant: 90),
      productImageView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 8),
      productImageView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -8),

      statusLabel.topAnchor.constraint(equalTo: productImageView.topAnchor),
      statusLabel.trailingAnchor.constraint(equalTo: productImageView.trailingAnchor),
      statusLabel.widthAnchor.constraint(equalToConstant: 36),
      statusLabel.heightAnchor.constraint(equalToConstant: 18),

      nameLabel.topAnchor.constraint(equalTo: productImageView.topAnchor),
      nameLabel.leadingAnchor.constraint(equalTo: productImageView.trailingAnchor, constant: 8),
      nameLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -8),

      statsLabel.topAnchor.constraint(equalTo: nameLabel.bottomAnchor, constant: 8),
      statsLabel.leadingAnchor.constraint(equalTo: nameLabel.leadingAnchor),
      statsLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -8),

      priceLabel.centerYAnchor.constraint(equalTo: shareButton.centerYAnchor),
      priceLabel.leadingAnchor.constraint(equalTo: nameLabel.leadingAnchor),

      likeButton.centerYAnchor.constraint(equalTo: shareButton.centerYAnchor),
      likeButton.trailingAnchor.constraint(equalTo: shareButton.leadingAnchor, constant: -4),
      likeButton.widthAnchor.constraint(equalToConstant: 28),
      likeButton.heightAnchor.constraint(equalToConstant: 28),

      shareButton.bottomAnchor.constraint(equalTo: productImageView.bottomAnchor),
      shareButton.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -8),
      shareButton.widthAnchor.constraint(equalToConstant: 54),
      shareButton.heightAnchor.constraint(equalToConstant: 28),
    ])
  }

  func configure(with product: Product) {
    nameLabel.text = product.spuName

    if let imageUrl = URL(string: product.mainImage) {
      productImageView.kf
        .setImage(
          with: imageUrl,
          placeholder: UIImage(named: "login_image_logo")
        )
    }

    // 格式化价格显示
    let priceFormatter = NumberFormatter()
    priceFormatter.numberStyle = .decimal
    priceFormatter.minimumFractionDigits = 2
    priceFormatter.maximumFractionDigits = 2

    //        if let formattedPrice = priceFormatter.string(from: NSNumber(value: product.promotionPrice)) {
    //            priceLabel.text = "¥\(formattedPrice)"
    let fullString = "¥\(product.promotionPrice)"
    let attributedString = NSMutableAttributedString(string: fullString)

    // 设置"¥"的字体小一点
    attributedString.addAttributes(
      [
        .font: UIFont.systemFont(ofSize: 12, weight: .bold)  // 小号字体
      ], range: NSRange(location: 0, length: 1))

    // 设置价格部分的字体大一点
    attributedString.addAttributes(
      [
        .font: UIFont.systemFont(ofSize: 18, weight: .bold)  // 大号字体，可加粗
      ], range: NSRange(location: 1, length: (fullString as NSString).length - 1))

    priceLabel.attributedText = attributedString
    //        }

    // 格式化GMV显示（添加千位分隔符）
    //        if let formattedGMV = "\(NSNumber(value: product.gmv))" {
    //            if let formattedGMV = priceFormatter.string(from: NSNumber(value: product.gmv)) {
    // 创建富文本
    let attributedText = NSMutableAttributedString()

    // 添加"已售"文本
    attributedText.append(
      NSAttributedString(
        string: "已售",
        attributes: [
          .font: UIFont.systemFont(ofSize: 12),
          .foregroundColor: UIColor.gray,
        ]
      ))

    // 添加销售数量
    attributedText.append(
      NSAttributedString(
        string: "\(product.saleCount)",
        attributes: [
          .font: UIFont.systemFont(ofSize: 12),
          .foregroundColor: UIColor(red: 241 / 255, green: 123 / 255, blue: 69 / 255, alpha: 1),
        ]
      ))

    // 添加", 总GMV"文本
    attributedText.append(
      NSAttributedString(
        string: ", 总GMV",
        attributes: [
          .font: UIFont.systemFont(ofSize: 12),
          .foregroundColor: UIColor.gray,
        ]
      ))

    // 添加GMV数值
    attributedText.append(
      NSAttributedString(
        string: "¥\(product.gmv)",
        attributes: [
          .font: UIFont.systemFont(ofSize: 12),
          .foregroundColor: UIColor(red: 241 / 255, green: 123 / 255, blue: 69 / 255, alpha: 1),
        ]
      ))

    statsLabel.attributedText = attributedText
    //        }

    // 设置商品状态标签
    switch product.publishStatus {
    case 1:
      statusLabel.text = "上架中"
      statusLabel.backgroundColor = UIColor(
        red: 0 / 255, green: 191 / 255, blue: 126 / 255, alpha: 1)
      nameLabel.textColor = .black
    case 0:
      statusLabel.text = "待上架"
      statusLabel.backgroundColor = UIColor(
        red: 25 / 255, green: 139 / 255, blue: 254 / 255, alpha: 1)
      nameLabel.textColor = .gray
    default:
      statusLabel.text = "隐藏品"
      statusLabel.backgroundColor = .gray
      nameLabel.textColor = .lightGray
    }

    // 设置收藏状态
    let heartImage = product.followStatus == 1 ? "like_icon_success" : "like_icon_add"
    let bgColor =
      product.followStatus == 1
      ? UIColor(red: 224 / 255, green: 224 / 255, blue: 244 / 255, alpha: 1)
      : UIColor(red: 254 / 255, green: 46 / 255, blue: 46 / 255, alpha: 1)
    //        let config = UIImage.SymbolConfiguration(pointSize: 22)
    //        likeButton.setImage(UIImage(systemName: heartImage, withConfiguration: config), for: .normal)
    likeButton.setImage(UIImage(named: heartImage), for: .normal)
    likeButton.backgroundColor = bgColor
  }

  @objc private func likeAction() {
    onLikeButtonTapped?()
  }

  @objc private func shareAction() {
    onShareButtonTapped?()
  }
}

// MARK: - CategoryCell
class CategoryCell: UITableViewCell {
  private let nameLabel: UILabel = {
    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false
    label.textAlignment = .center
    return label
  }()

  override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    setupUI()
  }

  required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }

  private func setupUI() {
    contentView.addSubview(nameLabel)

    NSLayoutConstraint.activate([
      nameLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 8),
      nameLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
      nameLabel.centerYAnchor.constraint(equalTo: contentView.centerYAnchor),
      nameLabel.heightAnchor.constraint(equalToConstant: 44),
    ])
  }

  func configure(with category: Category) {
    if category.name == "爆品" {
      nameLabel.text = category.name! + "🔥"
    } else {
      nameLabel.text = category.name
    }
    backgroundColor = category.isSelected ? .white : .systemGray6

    // 更新选中和未选中状态的字体和颜色
    if category.isSelected {
      nameLabel.textColor = UIColor(red: 241 / 255, green: 123 / 255, blue: 69 / 255, alpha: 1)  // 橙色 #F17B45
      nameLabel.font = .systemFont(ofSize: 14, weight: .bold)
    } else {
      nameLabel.textColor = UIColor(red: 102 / 255, green: 102 / 255, blue: 102 / 255, alpha: 1)  // 灰色 #666666
      nameLabel.font = .systemFont(ofSize: 14, weight: .regular)
    }
  }
}
